# coding: utf-8
import pandas
from analyze.douban_data import douban_datas
from plotly.graph_objs import Scatter, Figure, Layout
import re
import plotly


class c_analyze:
    def __init__(self):
        self.douban = douban_datas()

    def get_data(self):
        self.data = self.douban.get_movie_data()
        df = pandas.DataFrame(self.data)
        del df["_id"]
        df = df[['title', 'commend', 'open_date', 'country', 'actor']]

        self.titles = list(df['title'])
        self.countrys = list(df['country'])
        self.actors = list(df['actor'])

        open_date = list(df['open_date'])
        self.years = []
        pattern = re.compile(r'(\d{4})')
        for item in open_date:
            if item:
                # print(item)
                try:
                    mt = pattern.search(item)
                except:
                    mt = None
                if mt:
                    items = mt.groups()[0]
                    self.years.append(items)
                else:
                    self.years.append(None)
            else:
                self.years.append(None)

        commend = list(df['commend'])
        self.rates = []
        for item in commend:
            self.rates.append(item['average'])
        self.rates = list(map(float, self.rates))

    def get_data_country(self, country):
        data = self.douban.get_movie_data_for_where(country)
        return data

    def zhexiantu(self):
        self.get_data()
        plotly.offline.plot([Scatter(x=self.titles, y=self.rates)])

    # 电影逐年评分大于9数量柱状图
    def zhuzhuangtu(self):
        self.get_data()
        df = pandas.DataFrame(self.titles, columns=['titles'])
        df['years'] = self.years
        results = list(map(float, self.rates))
        df['rates'] = results

        df = df[df.rates > 9]
        countyear = pandas.Series(list(df['years'])).value_counts().sort_index()
        # print(countyear)
        data = plotly.graph_objs.Data([
            plotly.graph_objs.Bar(
                x=countyear.index,
                y=countyear.values
            )
        ])
        layout = Layout(
            title='电影逐年评分大于9数量柱状图',
            yaxis={'title': '评分'},
            font=plotly.graph_objs.Font(
                family='Raleway, sans-serif'
            ),
            showlegend=False,
            xaxis=plotly.graph_objs.XAxis(
                tickangle=-45,
                title="年份"
            ),
            bargap=0.05
        )
        fig = Figure(data=data, layout=layout)
        plotly.offline.plot(fig)

    def sandiantu(self):
        self.get_data()
        df = pandas.DataFrame(self.titles, columns=['titles'])
        df['years'] = self.years
        df['rates'] = self.rates
        rateyear = df.groupby('years').mean()
        countyear = pandas.Series(list(df['years'])).value_counts().sort_index()
        print(countyear)
        print(rateyear.rates)

        data_g = []
        tr_x = Scatter(
            x=countyear.index,
            y=countyear.values,
            text=countyear.values,
            customdata='数量',
            textposition='top center',
            mode='text+customdata',
            name='y'
        )
        data_g.append(tr_x)

        layout = Layout(title="电影逐年高分分布图", xaxis={'title': '年份'}, yaxis={'title': '评分'})
        fig = Figure(data=data_g, layout=layout)
        plotly.offline.plot(fig)

    # 去重
    def process_data(self, datas):
        list = []
        for data in datas:
            items = data.split("/")
            for item in items:
                item = item.strip()
                if item == '中国大陆':
                    item = '中国'
                elif item =='USA':
                    item = '美国'
                elif item == '加拿大 Canada':
                    item = '加拿大'
                if item not in list:
                    list.append(item)
        return list

    def bingzhuangtu(self):
        self.get_data()
        df = pandas.DataFrame(self.titles, columns=['titles'])
        df['years'] = self.years
        df['rates'] = self.rates
        df['countrys'] = self.countrys

        countrysdf = df['countrys'].value_counts()
        countrys = self.process_data(countrysdf.index)
        list = []
        for country in countrys:
            count = 0
            for index in countrysdf.index:
                if country in index:
                    count += 1
            list.append(count)

        print(countrys)
        print(list)
        data_g = []
        tr_p = plotly.graph_objs.Pie(
            labels=countrys,
            values=list
        )
        data_g.append(tr_p)
        layout = Layout(title="电影高分国家占比")
        fig = Figure(data=data_g, layout=layout)
        plotly.offline.plot(fig)

    def guojianianfeng(self):
        self.get_data()
        df = pandas.DataFrame(self.titles, columns=['titles'])
        df['years'] = self.years
        df['rates'] = self.rates
        df['countrys'] = self.countrys
        countrysdf = df["countrys"].value_counts()
        countrys = self.process_data(countrysdf.index)
        data_g = []
        for country in countrys:
            list = []
            for index, row in df.iterrows():
                if country in row.countrys:
                    list.append({"rates": row.rates, "years": row.years})
            counteser = pandas.DataFrame(list)
            # print(counteser)
            resultdf = counteser.groupby('years').size()
            # print(resultdf)
            tr_1 = Scatter(
                x=resultdf.index,
                y=resultdf.values,
                text=resultdf.values,
                mode='lines',
                name=country,
                fill='tozeroy'  # 填充方式: 到x轴
            )
            data_g.append(tr_1)
        layout = Layout(title="国家电影逐年高分数量统计图", xaxis={'title': '年份'}, yaxis={'title': '数量'})
        fig = Figure(data=data_g, layout=layout)
        plotly.offline.plot(fig)
